package cn.iocoder.yudao.module.ai.tool.function;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.annotation.JsonClassDescription;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyDescription;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.ai.chat.model.ToolContext;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.function.BiFunction;

/**
 * 工具：工单审批
 * <p>
 * 同时，也是展示 ToolContext 上下文的使用
 *
 * @author Ren
 */
@Component("approval_sheet")
public class ApprovalSheetCreateToolFunction
        implements BiFunction<ApprovalSheetCreateToolFunction.Request, ToolContext,String> {


    @Data
    @JsonClassDescription("审批系统中的工单")
    public static class Request {

        /**
         * 工单号
         */
        @JsonProperty(required = true, value = "workTickets")
        @JsonPropertyDescription("工单号，必填字段")
        private String workTickets;

        /**
         * 审批状态
         */
        @JsonProperty(required = true, value = "approvalStatusStr")
        @JsonPropertyDescription("审批状态，必填字段，1-通过，3-拒绝")
        private String approvalStatusStr;

        /**
         * 拒绝理由
         */
        @JsonProperty(required = false, value = "rejectReason")
        @JsonPropertyDescription("拒绝理由，审批状态为3时必填")
        private String rejectReason;

    }


    @Override
    public String apply(Request request, ToolContext toolContext) {
        if (StrUtil.isEmpty(request.getWorkTickets())) {
            return "请输入工单号";
        }
        Map<String, Object> map = new HashMap<>();
        map.put("workTicket", request.getWorkTickets());
        if (StrUtil.isEmpty(request.getRejectReason())) {
            map.put("status", "1");
        }else {
            map.put("status", request.getApprovalStatusStr());
        }
        if (request.getApprovalStatusStr().equals("3")&&StrUtil.isEmpty(request.getRejectReason())){
            map.put("reason", "具体原因请询问审批人");
        }else {
            map.put("reason", request.getRejectReason());
        }
        String result = HttpUtil.createPost("http://192.168.1.168:38090/admin-api/storeroom/work-sheets/sheetsApproval")
                .addHeaders(Map.of("Authorization", "d115a01f765b4b2987e46116efd08d7f"))
                .body(JSONObject.toJSONString(map))
                .execute()
                .body();
        return result;
    }

}
